<template>
  <el-dialog :title=title1 width="600" v-model="visible"
             :close-on-click-modal="false" :destroy-on-close="true" draggable>
    <el-form ref="menuDialogFormRef" :model="state.ruleForm" :rules="dataRules" label-width="90px" v-loading="loading" v-if="flag === true">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="住户姓名" prop="residentName">
            <el-input v-model="state.ruleForm.residentName" clearable placeholder="请输入住户姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="住户电话" prop="phone">
            <el-input v-model="state.ruleForm.phone" clearable placeholder="请输入住户电话"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-button @click="query" class="ml10" icon="search" type="primary">
        查询
      </el-button>
      <el-button @click="resetQuery" icon="Refresh">
        重置
      </el-button>

    </el-form>
    <el-table
        :data="residentList"        style="width: 100%"
        v-loading="state.loading"
        @selection-change="handleResidentSelectionChange"
        border
    >
      <el-table-column type="selection" show-overflow-tooltip width="auto"></el-table-column>
      <el-table-column label="序号" type="index" show-overflow-tooltip width="auto"></el-table-column>
      <el-table-column label="住户姓名" prop="residentName" width="auto"></el-table-column>
      <el-table-column label="住户电话" prop="phone" width="auto"></el-table-column>
    </el-table>
    <template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">{{ confirmText }}</el-button>
			</span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="propertyResidentDialog">
import {useMessage} from '/@/hooks/message';
import { getResidentList, getUnResidentList, deleteResident, addResident } from "/@/api/room/room";

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh1']);
// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/IconSelector/index.vue'));


// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const menuDialogFormRef = ref();
const title1 = ref('');
const residentList = ref([]);
const confirmText = ref('');
const flag = ref(false);
const flag1 = ref(false);
// 多选rows
const selectObjs = ref([]) as any;
const selectedResidents = ref([]) as any;
// 是否可以多选
const multiple = ref(true);
// 定义需要的数据
const state = reactive({
  ruleForm: {
    roomId: '',
    residentId: '',
    residentName: '',
    phone: '',
    residentGender: '',
    remark: ''
  },
});


// 打开弹窗
const openResidentDialog = async (title: string, text: string, row?: any) => {
  visible.value = true;
  title1.value = title;
  confirmText.value = text;
  nextTick(() => {
    Object.assign(state.ruleForm, {
      residentId: '',
      residentName: '',
      phone: '',
      residentGender: '',
      remark: ''
    });
  });
  selectedResidents.value = []; // 清空之前的选择
  state.ruleForm.roomId = row;
  if (title1.value === "关联人员") {
    flag.value = false;
    let res = await getResidentList(row);
    residentList.value = res.data.data;
    selectObjs.value = [];
  } else {
    flag.value = true;
    state.ruleForm.roomId = row;
    let res = await getUnResidentList(state.ruleForm);
    residentList.value = res.data.data;
    selectObjs.value = [];
  }
};

const query = async () => {
  let res = await getUnResidentList(state.ruleForm);
  residentList.value = res.data.data;
};

const resetQuery = async () => {
  state.ruleForm.residentName = '';
  state.ruleForm.phone = '';
  await query();
};

// 关联用户删除
const deleteRelativeResident = async (ids: string[], roomId: string) => {
  try {
    loading.value = true;
    await deleteResident(ids, roomId);
    useMessage().success('删除成功');
    emit('refresh1');
  } catch (err: any) {
    useMessage().error('删除失败');
  }
}

const addRelativeResident = async (ids: string[], roomId: string) => {
  try {
    loading.value = true;
    await addResident(ids, roomId);
    useMessage().success('新增成功');
    emit('refresh1');
  } catch (err: any) {
    useMessage().error('新增失败');
  }
};

// 保存数据
const onSubmit = async () => {
  try {
    loading.value = true;
    if (title1.value === "关联人员") {
      const residentIds = selectedResidents.value.map((resident: any) => resident.residentId);
      await deleteRelativeResident(residentIds, state.ruleForm.roomId);
    } else {
      const residentIds = selectedResidents.value.map((resident: any) => resident.residentId);
      await addRelativeResident(residentIds, state.ruleForm.roomId);
    }
    visible.value = false;
    emit('refresh1');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};



const handleResidentSelectionChange = (objs: any[]) => {
  selectedResidents.value = objs;
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
  openResidentDialog,
});
</script>
